package com.genewoo.jta.plugin;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.UnknownHostException;

import de.mud.jta.FilterPlugin;
import de.mud.jta.Plugin;
import de.mud.jta.PluginBus;
import de.mud.jta.event.SocketListener;

public class Recorder extends Plugin implements FilterPlugin{

	public Recorder(PluginBus bus, String id) {
		super(bus, id);
		
//	    bus.registerPluginListener(new TelnetCommandListener(){
//
//			public void sendTelnetCommand(byte command) throws IOException {
//				System.out.println(command);
//				
//			}
//	    	
//	    }
//	    );
		bus.registerPluginListener(new SocketListener() {

			public void connect(String host, int port) throws UnknownHostException, IOException {
				starttime = System.currentTimeMillis();
				try {
					fw = new FileWriter("d:\\test.log");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

			public void disconnect() throws IOException {
				if (fw != null) {
					fw.close();
					System.out.println("end");
					fw = null;
				}			
			}
			
		});
		// TODO Auto-generated constructor stub

	}
	  
	  private FileWriter fw;
	  private long starttime;
	  
	  protected FilterPlugin source;

	  public void setFilterSource(FilterPlugin source) {
		System.out.println(source);
	    this.source = source;
	  }

	  public FilterPlugin getFilterSource() {
	    return source;
	  }

	  public int read(byte[] b) throws IOException {
//		  printBytes(b);
		return source.read(b);
	  }

	  public void write(byte[] b) throws IOException {
		  printBytes(b);
	    source.write(b);
	  }
	  
	  private void printBytes(byte[] b) {
		for (int i = 0; i < b.length; i++) {
			try {
				fw.write((System.currentTimeMillis() - starttime) + ":" + b[i] + "\n");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println((System.currentTimeMillis() - starttime) + ":" + b[i]);
		}
	  }  

}
